package cc.orange.base;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.DisplayCutout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowInsets;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import android.os.Build;


import java.util.List;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
import cc.orange.R;

import cc.orange.utils.StatusBarUtilView;
import cc.orange.utils.ZXToastUtil;
import demo.smart.access.xutlis.util.ZXSharedPrefUtil;


/**.
 */
public abstract class BaseActivity extends AppCompatActivity{

    private Toast toast;
    private AlertDialog dialog;
    private ImageView ivLoading;
    private TextView iv_loading_text;
    private AnimationDrawable animationDrawable;
    private long lastClickTime;



    //    private Unbinder unbinder;
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(getContentView());
//        unbinder = ButterKnife.bind(this);
//
//        initView();
//        initListener();
//        initData();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);


        // 清除已存在的 Fragment 防止因没有复用导致叠加显示
        clearAllFragmentExistBeforeCreate();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setNavigationBarColor(Color.parseColor("#111111"));
            //getWindow().setNavigationBarColor(getResources().getColor(R.color.black));
            //getWindow().setNavigationBarColor(Color.BLUE);
        }

    }

    @Override
    public boolean moveTaskToBack(boolean nonRoot) {
        return super.moveTaskToBack(true);
    }

    private DisplayCutout cutoutDisp = null;
    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        initViewTabs();
    }

    public void initViewTabs() {
        //挖孔屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            try{
                WindowInsets windowInsets = getWindow().getDecorView().getRootWindowInsets();
                if (windowInsets != null) {
                    cutoutDisp = windowInsets.getDisplayCutout();
                }
            }catch (Exception e){
            }
//            if(cutoutDisp != null){
//                WindowManager.LayoutParams windowManagerDu = getWindow().getAttributes();
//                windowManagerDu.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
//                getWindow().setAttributes(windowManagerDu);
////                StatusBarUtilView.setLightStatusBar(BaseActivity.this,true,false);
//                StatusBarUtilView.setStatusBarColor(BaseActivity.this,R.color.white);
//                StatusBarUtilView.setLightStatusBar(BaseActivity.this,true,false);
//
//            }else {
                WindowManager.LayoutParams windowManagerDu = getWindow().getAttributes();
                windowManagerDu.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
                getWindow().setAttributes(windowManagerDu);
                StatusBarUtilView.setStatusBarColor(BaseActivity.this,R.color.white);
                StatusBarUtilView.setLightStatusBar(BaseActivity.this,true,false);
//            }
        }else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                StatusBarUtilView.transparencyBar(BaseActivity.this);
                StatusBarUtilView.setStatusBarColor(BaseActivity.this, R.color.white);
                StatusBarUtilView.setLightStatusBar(BaseActivity.this, true, false);

            }else {
                Window window = getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(getResources().getColor( R.color.black));
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }
        }
    }

    public void initViewTabs(int type) {
        //挖孔屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            try{
                WindowInsets windowInsets = getWindow().getDecorView().getRootWindowInsets();
                if (windowInsets != null) {
                    cutoutDisp = windowInsets.getDisplayCutout();
                }
            }catch (Exception e){
            }
//            if(cutoutDisp != null){
//                WindowManager.LayoutParams windowManagerDu = getWindow().getAttributes();
//                windowManagerDu.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
//                getWindow().setAttributes(windowManagerDu);
////                StatusBarUtilView.setLightStatusBar(BaseActivity.this,true,false);
//                StatusBarUtilView.setStatusBarColor(BaseActivity.this,R.color.white);
//                StatusBarUtilView.setLightStatusBar(BaseActivity.this,true,false);
//
//            }else {
            WindowManager.LayoutParams windowManagerDu = getWindow().getAttributes();
            windowManagerDu.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(windowManagerDu);
            StatusBarUtilView.setStatusBarColor(BaseActivity.this,type == 1 ? R.color.black_80 : R.color.white);
            StatusBarUtilView.setLightStatusBar(BaseActivity.this,true,false);
//            }
        }else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                StatusBarUtilView.transparencyBar(BaseActivity.this);
                StatusBarUtilView.setStatusBarColor(BaseActivity.this,type == 1 ? R.color.black_80 : R.color.white);
                StatusBarUtilView.setLightStatusBar(BaseActivity.this, true, false);

            }else {
                Window window = getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(getResources().getColor( R.color.black));
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }
        }
    }

    //获取状态栏高度
    public int getStatusBarHeight() {
        Context context = getApplicationContext();
        int result = 0;
        if(cutoutDisp != null){
            int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                result = context.getResources().getDimensionPixelSize(resourceId);
            }

        }
        return result;
    }

    //
////    @LayoutRes
//    protected abstract int getContentView();
//
//    protected abstract void initView();
//
//    protected abstract void initListener();
//
//    protected abstract void initData();

    public void showToast(String msg) {
//        cancelToast();
//        if (toast == null) {
//            toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
//        }
//        toast.show();
        ZXToastUtil.showToast(msg);
    }

    public void cancelToast() {
        if (toast != null) {
            toast.cancel();
            toast = null;
        }
    }

    public void showLoading_base(Context context) {
        if (dialog == null || ivLoading == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.layout_loading_lootom, null, false);
            ivLoading = (ImageView) view.findViewById(R.id.iv_loading);
            dialog = new AlertDialog.Builder(context, R.style.dialog_transparent).create();
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    if (ivLoading != null) {
                        ivLoading.clearAnimation();
                    }
                }
            });
            dialog.setCancelable(true);
            dialog.setView(view);
            dialog.getWindow().setDimAmount(0f);
        }

        animationDrawable = (AnimationDrawable) ivLoading.getDrawable();
        //开始动画
        animationDrawable.start();

        if (!dialog.isShowing()) {
            dialog.show();
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                cancelLoading();
            }
        }, 1000*5);
    }


    public void showLoading_base(Context context,String content,boolean visiable) {
        if (dialog == null || ivLoading == null) {
            View view = LayoutInflater.from(context).inflate(R.layout.layout_loading_lootom, null, false);
            ivLoading = (ImageView) view.findViewById(R.id.iv_loading);
            iv_loading_text =  (TextView) view.findViewById(R.id.iv_loading_text);
            dialog = new AlertDialog.Builder(context, R.style.dialog_transparent).create();
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    if (ivLoading != null) {
                        ivLoading.clearAnimation();
                    }
                }
            });
            if(!visiable){
                ivLoading.setVisibility(View.GONE);
            }
            iv_loading_text.setText(content);
            dialog.setCancelable(true);
            dialog.setView(view);
            dialog.getWindow().setDimAmount(0f);
        }

        animationDrawable = (AnimationDrawable) ivLoading.getDrawable();
        //开始动画
        animationDrawable.start();

        if (!dialog.isShowing()) {
            dialog.show();
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                cancelLoading();
            }
        }, !visiable ? 1200 : 10*1000);
    }

    public void cancelLoading() {
        if (dialog != null && dialog.isShowing()) {
//            if (ivLoading != null) {
//                ivLoading.clearAnimation();
//            }
            if (animationDrawable != null) {
                animationDrawable.stop();
            }
            dialog.dismiss();
        }
    }


    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }


    /**
     * 清除所有已存在的 Fragment 防止因重建 Activity 时，前 Fragment 没有销毁和重新复用导致界面重复显示
     * 如果有自己实现 Fragment 的复用，请复写此方法并不实现内容
     */
    public void clearAllFragmentExistBeforeCreate() {
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if (fragments.size() == 0) return;

        FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
        for (Fragment fragment : fragments) {
            fragmentTransaction.remove(fragment);
        }
        fragmentTransaction.commitNow();
    }

    /**
     * 是否监听退出应用操作，默认监听， 如果不像监听， 可复写
     * 此方法并返回 false
     *
     * @return
     */
    public boolean isObserveLogout() {
        return true;
    }

    private void registerLogoutBoardcast() {
        IntentFilter intentFilter = new IntentFilter("com.rong.im.action.logout");
        registerReceiver(logoutRecevier, intentFilter);
    }

    private void unRegisterLogoutBroadcast() {
        unregisterReceiver(logoutRecevier);
    }

    /**
     * 通知通其他注册了登出广播的 Activity 关闭
     */
    public void sendLogoutNotify() {
        //发送广播
        Intent intent = new Intent("com.rong.im.action.logout");
        sendBroadcast(intent);
    }

    private BroadcastReceiver logoutRecevier = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
        }
    };

    /**
     * 解决Fragment中的onActivityResult()方法无响应问题。
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 1.使用getSupportFragmentManager().getFragments()获取到当前Activity中添加的Fragment集合
         * 2.遍历Fragment集合，手动调用在当前Activity中的Fragment中的onActivityResult()方法。
         */
        if (getSupportFragmentManager().getFragments() != null && getSupportFragmentManager().getFragments().size() > 0) {
            List<Fragment> fragments = getSupportFragmentManager().getFragments();
            for (Fragment mFragment : fragments) {
                mFragment.onActivityResult(requestCode, resultCode, data);
            }
        }
    }


    /**
     * 为防止多次重复点击
     *
     * @return
     */
    public synchronized boolean isFastClick() {
        long time = System.currentTimeMillis();
        if (time - lastClickTime < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }


    public void initViewTabs1(int type) {
        //挖孔屏
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            try{
                WindowInsets windowInsets = getWindow().getDecorView().getRootWindowInsets();
                if (windowInsets != null) {
                    cutoutDisp = windowInsets.getDisplayCutout();
                }
            }catch (Exception e){
            }
//            if(cutoutDisp != null){
//                WindowManager.LayoutParams windowManagerDu = getWindow().getAttributes();
//                windowManagerDu.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
//                getWindow().setAttributes(windowManagerDu);
////                StatusBarUtilView.setLightStatusBar(BaseActivity.this,true,false);
//                StatusBarUtilView.setStatusBarColor(BaseActivity.this,R.color.white);
//                StatusBarUtilView.setLightStatusBar(BaseActivity.this,true,false);
//
//            }else {
            WindowManager.LayoutParams windowManagerDu = getWindow().getAttributes();
            windowManagerDu.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
            getWindow().setAttributes(windowManagerDu);
            StatusBarUtilView.setStatusBarColor(BaseActivity.this, R.color.black_0e);
            StatusBarUtilView.setLightStatusBar(BaseActivity.this,false,false);
//            }
        }else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
//                StatusBarUtilView.transparencyBar(BaseActivity.this);
                StatusBarUtilView.setStatusBarColor(BaseActivity.this,R.color.black_0e );
                StatusBarUtilView.setLightStatusBar(BaseActivity.this, false, false);

            }else {
                Window window = getWindow();
                window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(getResources().getColor( R.color.black_0e));
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            }
        }
    }

    public String getTokens(){
        ZXSharedPrefUtil sh = new ZXSharedPrefUtil();
        return sh.getString("token_talk","");
    }
}